package d20chat;

import java.util.Scanner;

import javax.swing.JOptionPane;


/********************************************************************************
Handles messages coming to the client.
********************************************************************************/
public class IncomingMessageParser 
{
    /** the ui component for displaying text. */
    private D20Chatui tempui;
    /**
     * where we can find information about the user.
     */
    private D20Chat theMain;
    /**
     * a copy of the message sent from the server.
     */
    private MessageInfo receivedMessage;
    /** the name of the last person to send a /tell */
    public String lastPerson = "";
    

    /**
     * Checks the type of message and sends it to the appropriate methods to handle it.
     * @param message a formatted message sent to the client
     */
    public void CheckType(String message)
    {
        //stores the message
        receivedMessage = new MessageInfo(message);

        //set the text of the message to be anything after the fourth word
        receivedMessage.text = receivedMessage.message.substring( receivedMessage.endOfWord4 );
                
        //check to see if the type is chat, command, or request and call the corresponding function
        if( receivedMessage.type.equals( "chat" ) )
        {
            //call the function chat() to format the final message that will display on the screen
            chat();
        }
        else if( receivedMessage.type.equals( "command" ) )
        {
            //call the function command to handle any client side chores and format final message
            command(); 
        }
        else if( receivedMessage.type.equals( "request" ) )
        {
            //call the function request to handle any client side chores and format final message
            request();
        }

    }
    
    
    /**
     * Handles messages that just needs to be formatted and displayed in the chat window.
     */
    private void chat()
    {
        String finalMessage = ""; //the string to hold the formatted message
        String format, endformat;
        if( theMain.theSettings.overwrite == true )
        {
            //if the user wants only font formatting originating from them
            //remove the html from the message
            stripHTML();
            format = "";
            endformat = "";
        } else if (theMain.extraSettings.colorAll)
        {
            format = receivedMessage.text.substring(0, receivedMessage.text.indexOf(";\">")+3);
            stripHTML();
            endformat = "</span>";
        } else
        {
            format = "";
            endformat = "";
        }
        
        if( receivedMessage.subType.equals("systemMessage"))
        {
            //add that it's a system message it and display it.
            finalMessage = "System Message : " + receivedMessage.text;
        }
        else if( receivedMessage.subType.equals("say"))
        {
            if( receivedMessage.originName.equals(theMain.theUser.getUsername()) )
            {
                //the say comes from this user so output it as coming from them
                String tempname = theMain.extraSettings.useSN ? theMain.theUser.getUsername() : "You";
                String tempsay = theMain.extraSettings.useColon ? ": " : theMain.extraSettings.useSN ? " says " : " say ";
                finalMessage = format + tempname + tempsay + receivedMessage.text + endformat;
            }
            else
            {
                //the say comes from another user, say who
                String tempsay = theMain.extraSettings.useColon ? ": " : " says ";
                finalMessage = format + receivedMessage.originName + tempsay + receivedMessage.text + endformat;
            }

        }
        else if( receivedMessage.subType.equals("emote"))
        {
                //say who is doing the emote
                //even if it's the user it makes more grammatical sense to use their name than you
                finalMessage = format + receivedMessage.originName + " " + receivedMessage.text + endformat;
        }
        else if( receivedMessage.subType.equals("tell"))
        {
            if( receivedMessage.originName.equals(theMain.theUser.getUsername()) )
            {
                //the tell comes from this user, so output it as coming from them
                finalMessage = "You tell " + receivedMessage.targetName + " " + format + receivedMessage.text + endformat;
            }
            else
            {
                lastPerson = receivedMessage.originName;
                //the tell comes from another user, say who
                finalMessage = format + receivedMessage.originName + " tells you " + receivedMessage.text + endformat;
            }
        }
        else if( receivedMessage.subType.equals("hide"))
        {
            if( receivedMessage.originName.equals(theMain.theUser.getUsername()) )
            {
                //a message from this user that is only seen by them, indicate that
                //by adding hidden to the message
                finalMessage = "Hidden : " + format + receivedMessage.text + endformat;
            }
        }

        //now that the message has been formatted display it in the chat window
        tempui.tempchatwindowoutput( finalMessage );
     }
    
    
    /**
     * Handles messages from or about players.
     * Responds to messages that require it.
     * Alters variables on client end if necessary.
     */
    private void request()
    {
        String info;
        String finalMessage;
        
        if( receivedMessage.subType.equals( "requestUserInfo" ) )
        {   
            info = "/userInfo " + theMain.theUser.toString();   
            theMain.OutParse.sendMessage( info );
        }
        else if( receivedMessage.subType.equals( "playersList" ) )
        {
            info = receivedMessage.text;

            String[] names = info.split("\u8594");
            tempui.playernames = names;

            tempui.refreshplayer();
        }
        else if( receivedMessage.subType.equals( "password" ) )
        {
            if( theMain.serverPassword.isEmpty() )
            {
                //pop up box asking for password and send would be better
                info = "/password empty";
                theMain.OutParse.sendMessage( info );
            }
            else
            {   
                //send password
                info = "/password " + theMain.serverPassword.toString();   
                theMain.OutParse.sendMessage( info );
            }
        }
        else if( receivedMessage.subType.equals( "profile" ) )
        {
            info = "junk " + receivedMessage.text;
            
            //Pop up ShowProfile form
            ShowProfile sp;
            sp = new ShowProfile(info);
            sp.setVisible(true);
        }
        else if( receivedMessage.subType.equals( "charsheet" ) )
        {
            info = "/sendcharsheet " + receivedMessage.originName + " " + tempui.getcharsheet();
            theMain.OutParse.sendMessage( info );
        }
        else if( receivedMessage.subType.equals( "sendcharsheet" ) )
        {
            info = receivedMessage.text;
            
            theMain.charV.openSheet(info);
            theMain.charV.setVisible(true);
            
        }
        else if( receivedMessage.subType.equals( "charNameChange" ) )
        {
            Scanner pieceScanner = new Scanner( receivedMessage.message );
            pieceScanner.useDelimiter( "\u8594" );

            if( pieceScanner.hasNext() )
            {
                //junk piece
             pieceScanner.next();

            }
            if( pieceScanner.hasNext() )
            {
                String newName = pieceScanner.next();
                tempui.changeplayer(receivedMessage.originName, receivedMessage.originName, newName);
            }
        }        
        else if( receivedMessage.subType.equals( "changeName" ))
        {
            finalMessage = receivedMessage.originName + " has changed their name to " + receivedMessage.targetName + "\n";
            tempui.changeplayer(receivedMessage.originName, receivedMessage.targetName, receivedMessage.text);
            tempui.tempchatwindowoutput( finalMessage );
        }
    }
    
    
    /**
     * Handles messages from gm or that effect everyone in the room.
     */
    private void command()
    {
        //this is messages about silence, kick, add, remove, charactersheets ect.
        
        String finalMessage = "";
        
        if( receivedMessage.subType.equals("silence"))
        {
            silence();
        }
        else if( receivedMessage.subType.equals( "kick" ))
        {
            finalMessage = "The GM has kicked " + receivedMessage.targetName +".\n";
            tempui.tempchatwindowoutput( finalMessage );
            
            // If the current client is the kickee then let the user know
            if (theMain.theUser.getUsername().equals(receivedMessage.targetName))
                JOptionPane.showMessageDialog(null, "You have been kicked from the room.", "D20 Chat", JOptionPane.ERROR_MESSAGE);
        }
        else if( receivedMessage.subType.equals( "charactersheet" ))
        {
            if( receivedMessage.state.equals( "on" ) )
            {
                finalMessage = "You may now view other player's charactersheets.\n";
            }
            else if( receivedMessage.state.equals( "off" ) )
            {
                finalMessage = "Other player's character sheets are now hidden.\n";
            }
            tempui.tempchatwindowoutput( finalMessage );
            
        }
        else if( receivedMessage.subType.equals( "leaveRoom" ))
        {
            finalMessage = receivedMessage.originName + " has left the room.\n";
            tempui.tempchatwindowoutput( finalMessage );
            tempui.removeplayer(receivedMessage.originName);
            
            // If the current client leaves the room then let the user know
            if (theMain.theUser.getUsername().equals(receivedMessage.originName))
                JOptionPane.showMessageDialog(null, "You have left the room.", "D20 Chat", JOptionPane.INFORMATION_MESSAGE);
        }
        else if( receivedMessage.subType.equals( "joinRoom" ))
        {
            finalMessage = receivedMessage.originName + " has joined the room.\n";
            tempui.tempchatwindowoutput( finalMessage );
            tempui.addplayer(receivedMessage.originName, receivedMessage.text );
        }
        else if( receivedMessage.subType.equals( "changeName" ))
        {
            finalMessage = receivedMessage.originName + " has changed their name to " + receivedMessage.targetName + "\n";
            tempui.tempchatwindowoutput( finalMessage );
            tempui.changeplayer(receivedMessage.originName, receivedMessage.targetName, receivedMessage.text);
        }
        else if( receivedMessage.subType.equals("makeGM"))
        {
            finalMessage = receivedMessage.targetName + " is now the GM.\n";
            tempui.tempchatwindowoutput( finalMessage );
        }
        else if( receivedMessage.subType.equals("map"))
        {
        	theMain.mapV.setMap(MapViewer.parseMap(receivedMessage.message.substring(receivedMessage.message.indexOf("DDMap"))));
        }
        else
        {
            //echo message for testing
            tempui.tempchatwindowoutput( receivedMessage.message );
        }

    }
    
    
    /**
     * Strips any text between < and > out of the message to remove html.
     */
     private void stripHTML()
    {
        //find text braketed by < and > in the unparsed message
        receivedMessage.message = receivedMessage.message.replaceAll("\\<.*?\\>","");
    }
     
     

    /**
     * Displays a message about silence action.
     */
    private void silence()
    {
        String action = "";

        if( receivedMessage.state.equals("on") )
        {
            if( receivedMessage.targetName.equalsIgnoreCase( theMain.theUser.getUsername() ) )
            {
                action = "The GM has silenced you.\n";
            }
            else if( receivedMessage.targetName.equalsIgnoreCase( "all" ) )
            {
                action = "The GM has silenced all players.\n";
            }
            else
            {
                action = "The GM has silenced " + receivedMessage.targetName + ".\n";
            }
        }
        else if( receivedMessage.state.equals("off") )
        {
             if( receivedMessage.targetName.equalsIgnoreCase( theMain.theUser.getUsername() ) )
            {
                action = "The GM has given you permission to speak.\n";
            }
            else if( receivedMessage.targetName.equalsIgnoreCase( "all" ) )
            {
                action = "The GM has given all players permission to speak.\n";
            }
            else
            {
                action = "The GM has given " + receivedMessage.targetName + " permission to speak.\n";
            }
        }

        tempui.tempchatwindowoutput ( action );
    }   
    
    
    /**
     * Creates a new instance of IncomingMessageParser
     * @param gui The user interface for the program.
     * @param thisD20Chat The main class for the program.
     */
    public IncomingMessageParser( D20Chatui gui, D20Chat thisD20Chat )
    {
        tempui = gui;
        theMain = thisD20Chat;
    }
}
